# coding=utf-8
import web,thread,json,sys,os,codecs

import random

import string
web.config.debug = False 
urls = ('/', 'index' ,
'/Server/Grid/','Grid',
'/Server/Upload/','Upload',
'/Server/Grid.aspx','Grid',
'/Server/Upload.aspx','Upload')
render = web.template.render('templates/')
Config={}
class Upload:
    def getFileName(self):
        ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
        print(ran_str)
        return ran_str+".png"
    def POST(self):     
        x = web.input(files={})
        filedir =Config.get("OrgnalImgFile") 
        files=x.files
        if 1==1:
            Original=filedir +'/'+self.getFileName()
            img=files.file.read()  
            fout = open(Original,'wb') 
            fout.write(img)
            fout.close()
            return json.dumps({"error":0})
        else:
            return {} 
class index:
    def Openejs(self):
         f = open('templates/body.ejs')  #设置文件对象
         str = f.read()     #将txt文件的所有内容读入到字符串str中
         f.close()   #将文件关闭
         return str
    def GET(self): 
        body= self.Openejs()
        html=render.index({})
        html=str(html)
        html=html.replace("{body}",body)
        return html
class Grid():
    def GET(self):
        db = web.input(_method='get')
        web.header('content-type', 'text/json')
        return self.getdb(db)
    def openjson(self,file):
        f = codecs.open(file,encoding='utf-8')
        _str = f.read()
        f.close()
        return  json.loads(_str)
    def getdb(self,Get): 
        root=Config.get("SaveFile")
        bdf=[]
        for i in os.listdir(root):
            if os.path.exists(os.path.join(root,i)):
                f=os.path.join(root,i)
                if os.path.isfile(os.path.join(f,'Drive.json')):
                    Drive=self.openjson(os.path.join(f,'Drive.json'))
                    Drive["Url"]="./../../../static/images/grids/"+i+ "/{z}/{x}_{y}.png"
                    bdf.append({"id":i,"title":i,"Drive":Drive,"src":"../static/images/grids/"+i+"/0/0_0.png"})
        return json.dumps({"Table":bdf})
    def POST(self):
        db = web.input(_method='post')
        web.header('content-type', 'text/json')
        return self.getdb(db)
class WebApplication(web.application):
    def run(self, port=8080,*middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))
class HttpServer:
    def Start(self,a,b):
        self.ImageServer.Start()
        pass
    def __init__(self,ImageServer=None,argv={}):
        self.ImageServer=ImageServer
        Config["Server"]=ImageServer
        Config["SaveFile"]=argv.get("SaveFile")
        Config["OrgnalImgFile"]=argv.get("OrgnalImgFile")
        thread.start_new_thread(self.Start,("Thread-1", 2, ) )
        Port=argv.get('Port')
        app =WebApplication(urls, globals())
        app.run(Port)
